// 橡皮筋滑屏效果
/**
 *
 * @param {} obj { wpar: 父盒子, swiper: 滚动的盒子, x: x|y 默认 y }
 * @returns
 */
export function createElastic(obj) {
  if (!obj) {
    obj = {};
  }
  const wrap = obj.wrap;
  const swiper = obj.swiper;

  let wrapWidth = wrap.clientHeight;
  let swiperHeight = swiper.clientHeight - wrapWidth;
  swiperHeight = swiperHeight <= 0 ? wrapWidth : swiperHeight;

  let start = 0;
  let scroll = false;
  let dis = 0; // 记录当前位移的距离
  let time = 0;
  let arrow = 1; // 方向正负
  let initStart = 0;
  let moveDis = 0; // 滑动的距离
  let initTime = 0;
  let timer = null; // 定时器
  let direct = 'clientY'; // 是纵向还是横向
  let disNumber = obj.disNumber || 280; // 快速滑动的距离，越大滑动的距离越大
  let springbackTime = obj.springbackTime || 0.4; // 回弹时间
  let springbackMaxDis = obj.springbackMaxDis || 150; // 回弹的最大距离
  let lastLetGo = 0;
  if (obj.direction === 'x') {
    direct = 'clientX';
    wrapWidth = wrap.clientWidth;
    swiperHeight = swiper.clientWidth - wrap.clientWidth;
  }

  // console.log('滑动高度', 'wrapWidth', wrapWidth, 'swiperHeight', swiperHeight,swiper,swiper.clientHeight);

  function trans(value) {
    if (obj.direction === 'x') {
      return `translate3d(${value},0,0)`;
    }
    return `translate3d(0,${value},0)`;
  }

  function ani(time, line) {
    if (!line) {
      line = 'cubic-bezier(.07,.2,.38,1)';
    }
    return `transform ${time} ${line}`;
  }

  function touchStart(e) {
    // console.log('触摸开始');
    if (swiperHeight <= 0) {
      swiperHeight = swiper.clientHeight - wrapWidth;
    }

    scroll = false;
    time = Date.now();
    initTime = time;
    start = e.targetTouches[0][direct];
    initStart = start;
    swiper.style.transition = ani(0 + 's');

    // console.log(e, swiper.style);
  }

  function touchMove(e) {
    // console.log('触摸移动');
    const disValue = e.targetTouches[0][direct] - start; // 滑动的距离
    const curArrow = disValue > 0 ? 1 : -1; // 判断方向
    if (arrow !== curArrow) {
      initStart = e.targetTouches[0][direct];
      initTime = Date.now();
      arrow = curArrow;
    }

    const curDis = dis; // 保存初始位移
    dis += disValue; // 当前要位移的距离

    // console.log(Date.now() - time)
    //  如果大于20就是慢慢滑动
    if (Date.now() - time > 50) {
      initStart = e.targetTouches[0][direct];
      // console.log('慢慢滑动')
    }

    // console.log(dis)
    if (dis >= 0) {
      // console.log(dis);
      // let proportion = 1 - (dis / wrapWidth) * 2;
      let proportion = wrapWidth / (wrapWidth * 3 + dis * 8);
      dis = curDis + proportion * disValue;
      swiper.style.transform = trans(dis + 'px');
    } else if (dis <= -swiperHeight) {
      // console.log(dis + swiperHeight);
      let proportion = wrapWidth / (wrapWidth * 3 + Math.abs(dis + swiperHeight) * 8);
      dis = curDis + proportion * disValue;
      swiper.style.transform = trans(dis + 'px');
    } else {
      swiper.style.transform = trans(dis + 'px');
    }

    lastLetGo = e.targetTouches[0][direct] - start;
    start = e.targetTouches[0][direct];
    moveDis = e.targetTouches[0][direct] - initStart;
    time = Date.now();
  }

  function touchEnd() {
    // console.log(Date.now() - time);
    // console.log('触摸结束');
    // console.log('嫉力度', moveDis / (Date.now() - initTime));
    scroll = true;
    let f = (moveDis / (Date.now() - initTime)) * 40;
    // let scrollTime = springbackTime;
    // const timeDis = 1500; // 距离/时间--系数
    // const originDis = dis;
    // const curMoveDIs = (moveDis / (Date.now() - initTime)) * disNumber;
    // 快速滑屏并且手指立马离开
    if (Date.now() - time <= 20 && dis < 0 && Math.abs(lastLetGo) > 3) {
      const fn = () => {
        if (!scroll) {
          return;
        }
        requestAnimationFrame(() => {
          dis += f * 0.7; // 每次位移的距离
          f *= 0.96; // 剩余力度
          swiper.style.transform = trans(dis + 'px');
          // console.log(f);
          if (dis > 0 + springbackMaxDis) {
            // 向上滑动超出
            dis = 0;
            swiper.style.transition = ani(springbackTime + 's');
            swiper.style.transform = trans(dis + 'px');
            return;
          }
          if (dis < -swiperHeight - springbackMaxDis) {
            // 滑倒底部超出
            dis = -swiperHeight;
            swiper.style.transition = ani(springbackTime + 's');
            swiper.style.transform = trans(dis + 'px');
            return;
          }
          if (Math.abs(f) > 5) {
            fn();
          } else {
            if (dis > 0) {
              // 向上滑动超出
              dis = 0;
              swiper.style.transition = ani(springbackTime + 's');
              swiper.style.transform = trans(dis + 'px');
              return;
            }
            if (dis < -swiperHeight) {
              // 滑倒底部超出
              dis = -swiperHeight;
              swiper.style.transition = ani(springbackTime + 's');
              swiper.style.transform = trans(dis + 'px');
              return;
            }
          }
        });
      };
      fn();
    } else {
      // 慢慢滑屏
      if (dis >= 0) {
        // 向上滑动超出
        dis = 0;
        swiper.style.transition = ani(springbackTime + 's');
        swiper.style.transform = trans(dis + 'px');
      }
      if (dis < -swiperHeight) {
        // 滑倒底部超出
        dis = -swiperHeight;
        swiper.style.transition = ani(springbackTime + 's');
        swiper.style.transform = trans(dis + 'px');
      }
    }

    // console.log(moveDis, Date.now() - initTime, Date.now() - time)
  }

  swiper.style.transform = trans(0);

  wrap.addEventListener('touchstart', touchStart);
  wrap.addEventListener('touchmove', touchMove);
  wrap.addEventListener('touchend', touchEnd);

  // 返回一个函数移除事件
  return () => {
    // console.log('移除事件啦')
    wrap.removeEventListener('touchstart', touchStart);
    wrap.removeEventListener('touchmove', touchMove);
    wrap.removeEventListener('touchend', touchEnd);
  };
}

export function plusReady() {
  // openPrivacy();
  // Android处理返回键
  plus.key.addEventListener(
    'backbutton',
    () => {
      // 'iOS' == plus.os.name
      //   ? plus.nativeUI.confirm(
      //       '确认退出？',
      //       function (e: any) {
      //         if (e.index > 0) {
      //           plus.runtime.quit();
      //         }
      //       },
      //       'HelloH5',
      //       ['取消', '确定']
      //     )
      //   : confirm('确认退出？') && plus.runtime.quit();
      console.log('手机系统', plus.os.name);
      if (plus.os.name === 'iOS') {
        confirm('确认退出？') && plus.runtime.quit();
      } else {
        // 如果是安卓
        window.history.go(-1);
      }
    },
    false
  );
  // 关闭启动界面
  // plus.navigator.setStatusBarBackground('#D74B28');
  setTimeout(function () {
    plus.navigator.closeSplashscreen();
  }, 200);
}

// 验证邮箱格式
export const valideEmail = (str) => /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/.test(str);

// 获取hash路路由
export const getHash = () => {
  let str = window.location.hash;
  if (str.length > 0) {
    str = str.substring(1);
    // console.log('hash值', str);
  }
  return str.split('?')[0];
};

// 对象转get参数
export const objToStringParams = (obj) => {
  if (Reflect.apply(toString, obj, []) !== '[object Object]') {
    return '';
  }
  let str = '?';
  Object.keys(obj).forEach((key) => {
    str += `${key}=${obj[key]}`;
  });
  if (str.length > 1) {
    return str;
  }
  return '';
};

// img转base64
export const getBase64Image = (img) => {
  let canvas = document.createElement('canvas');
  canvas.width = img.width;
  canvas.height = img.height;

  const ctx = canvas.getContext('2d');
  ctx.drawImage(img, 0, 0, img.width, img.height);

  const dataURL = canvas.toDataURL('image/png', 1.0);
  canvas = null;
  return dataURL;
};

// 简单的拖动dom
export const dragDom = (dom) => {
  if (!/HTML/.test(Reflect.apply(Object.prototype.toString, dom, []))) {
    console.error('拖动元素请传入要拖动的dom');
    return;
  }

  let pageX = 0;
  let pageY = 0;
  let parentWidth = 0;
  let parentHeight = 0;
  const parent = dom.parentNode;
  let allowMove = false;
  const sty = window.getComputedStyle(dom);
  let left = parseInt(sty.left);
  let top = parseInt(sty.top);
  dom.style.left = sty.left;
  dom.style.top = sty.top;

  const touchstart = (e) => {
    const touch = e.targetTouches[0];
    pageX = touch.pageX;
    pageY = touch.pageY;
    const rectParent = parent.getBoundingClientRect();
    const rectDom = dom.getBoundingClientRect();
    parentWidth = rectParent.width - rectDom.width;
    parentHeight = rectParent.height - rectDom.height;
    allowMove = true;
    left = parseInt(sty.left);
    top = parseInt(sty.top);
    // console.log(window.getComputedStyle(dom.parentNode).position)
  };

  const touchmove = (e) => {
    const touch = e.targetTouches[0];

    if (touch.pageX > document.body.clientWidth || touch.pageX <= 0) {
      allowMove = false;
      return;
    }
    if (touch.pageY > document.body.clientHeight || touch.pageY <= 0) {
      allowMove = false;
      return;
    }
    const moveX = touch.pageX - pageX;
    const moveY = touch.pageY - pageY;
    // console.log(moveY, moveX);
    left += moveX;
    top += moveY;
    // console.log(touch.pageX, touch.pageY);
    if (left <= 0 || left > parentWidth) {
      allowMove = false;
      return;
    }

    if (top <= 0 || top > parentHeight) {
      allowMove = false;
      return;
    }

    if (!allowMove) {
      return;
    }

    dom.style.left = left + 'px';
    dom.style.top = top + 'px';
    pageX = touch.pageX;
    pageY = touch.pageY;
  };
  const touchend = (e) => {
    // console.log(e);
    allowMove = false;
  };

  dom.addEventListener('touchstart', touchstart);
  dom.addEventListener('touchmove', touchmove);
  dom.addEventListener('touchend', touchend);
  return () => {
    dom.removeEventListener('touchstart', touchstart);
    dom.removeEventListener('touchmove', touchmove);
    dom.removeEventListener('touchend', touchend);
  };
};

export default {
  plusReady,
};
